// 二次封装axios
import router from "@/router";
import axios from "axios";
import { Toast, showLoadingToast, closeToast, showToast } from "vant";
import { useUserStore } from "@/stores/user";
//  axios的配置
const baseURL = "/api";
const request = axios.create({
  baseURL,
  timeout: 10000,
});
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    config.headers = {
      ...(config.headers || {}),
    };
    const token = userStore?.userInfo?.token;
    if (token) {
      config.headers.Authorization = `bearer ${token}`;
    }
    return config;
  },
  (err) => Promise.reject(err)
);
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    // 统一处理业务码 401
    const code = res?.data?.code;
    if (code == 401) {
      const userStore = useUserStore();
      userStore.logout();
      showToast("登录过期，请重新登录");
      setTimeout(() => {
        router.replace(`/login`);
      }, 1000);
      return Promise.reject(res?.data || { code: 401 });
    }
    return res.data;
  },
  (err) => {
    // 统一处理网络层 401
    const status = err?.response?.status;
    const code = err?.response?.data?.code;
    if (status === 401 || code == 401) {
      const userStore = useUserStore();
      userStore.logout();
      showToast("登录过期，请重新登录");
      setTimeout(() => {
        router.replace(`/login`);
      }, 1000);
    }
    return Promise.reject(err);
  }
);

export default request;
